package com.jy.api.domain;

import com.aliyun.opensearch.sdk.dependencies.org.json.JSONArray;
import com.aliyun.opensearch.sdk.dependencies.org.json.JSONObject;
import com.jy.api.signUpReq.admin.ProductSignUpReq;
import com.jy.api.util.PinYinUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by hanxi on 2017/7/8.
 * 商品表
 */
@Slf4j
@Entity
@Data
@NoArgsConstructor
@NamedEntityGraph(name = "Product.productType", attributeNodes = @NamedAttributeNode("productType"))
public class Product {
    @Id
    @Column(length = 50)
    private String id;
    private String storeId;
    private String name;
    private String pinyin;
    private String barCode;
    @ManyToOne
    private ProductType productType;
    private double costPrice = 0;
    private double salesPrice = 0.0;
    private String supplierName;
    private ProductStatus productStatus = ProductStatus.ON;
    private String imageURL;
    @Column(insertable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date addTime;
    @Column(insertable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date updateTime;
    private boolean enabled = true;
    private int quantity = 0;
    private String parentTypeName;

    @OneToMany(cascade = CascadeType.ALL)
    @Where(clause = "`enabled`=1")
    @JoinColumn(name = "product_id")
    private List<Spec> specs = new ArrayList<>();
    /**
     * 零售单位与库存单位的比率。比如一条烟等于10包，该值为10
     *
     * @deprecated 即将转移到Inventory
     */
    private int stockQuantityRatio = 1;
    /**
     * 库存单位价格
     *
     * @deprecated 即将转移到Inventory
     */

    private int stockPrice = 0;

    @Temporal(TemporalType.TIMESTAMP)
    private Date lastCheckTime;
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastStockInTime;
    /**
     * 是否管理库存
     */
    private boolean stockEnabled = true;
    /**
     * 是否允许会员赠送金额支付
     */
    private boolean allowMemberBonusPay = false;


    private boolean giftEnabled = false;
    // 1代表会员等级折扣  2另设价格   3 无折扣
    private int discountMethod = 0;

    @OneToMany(cascade = CascadeType.ALL)
    @OrderBy(value = "addTime")
    @JoinColumn(name = "product_id")
    private List<MemberLevelPrice> prices=new ArrayList<>();

    private boolean depositEnabled = false;

    private boolean discountEnabled = true;

    private String week;


    /**
     * 是否管理原材料
     */
    @Column(name = "is_material_enabled")
    private boolean materialEnabled = false;

    /**
     * 是否支持厨房打印
     */
    private boolean kitchenPrintEnabled = false;

    private String supplyTimes;

    /**
     * 是否进行热敏打印
     */
    private boolean isDirectThermal = false;

    private double memberPrice = 0.0;

    private boolean memberShow = false;

    private double disPrice = 0.0;

    private boolean disShow = false;

    private String nowHours = "00:00:00";

    private String tomorrowHour = "00:00:00";

    private boolean cross = false;

    private int setMealId = 0;

    private int setMealQty = 1;

    private boolean labelEnabled=false;

    private int ipId=0;

    private String ipName="";

    private int port=0;

    private String ipAddress="";

    /**
     * 修改时段
     *
     * @param productSupplyTime
     */
    public void updateSupplyTimes(ProductSupplyTime productSupplyTime) {
        if (supplyTimes.indexOf(productSupplyTime.getId()) != -1) {
            JSONArray jsonArray = new JSONArray(supplyTimes);
            int subscript = 0;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String supplyTimeId = jsonObject.getString("id");
                if (StringUtils.equals(id, supplyTimeId)) {
                    subscript = i;
                    break;
                }
            }
            jsonArray.remove(subscript);
            JSONObject jsonObject = new JSONObject(productSupplyTime);
            jsonArray.put(jsonObject);
            supplyTimes = jsonArray.toString();
        }

    }

    public Product(ProductSignUpReq req, ProductType type) {
        this.id = UUID.randomUUID().toString();
        this.storeId = req.getStoreId();
        this.name = req.getName();
        this.pinyin = PinYinUtil.getFirstSpell(req.getName());
        this.productType = type;
        this.salesPrice = req.getSalesPrice();
        this.imageURL = req.getImageURL();
        this.parentTypeName = type.getName();
        this.supplyTimes = req.getSupplyTimes();
        this.memberPrice = req.getMemberPrice();
        this.memberShow = req.isMemberShow();
        this.disPrice = req.getDisPrice();
        this.disShow = req.isDisShow();
        this.nowHours = req.getNowHours();
        this.tomorrowHour = req.getTroHours();
        this.kitchenPrintEnabled = req.isKitchenPrintEnabled();
        this.stockEnabled = req.isStockEnabled();
        this.giftEnabled = req.isGiftEnabled();
        // 1代表会员等级折扣  2另设价格   3 无折扣
        this.discountMethod = req.getDiscountMethod();
        this.depositEnabled = req.isDepositEnabled();
        this.week=req.getWeek();
        this.discountEnabled = req.isDiscountEnabled();
        List<MemberLevelPrice> prices = new ArrayList<>();
        for (ProductSignUpReq.Prices p:req.getPrices()){
            MemberLevelPrice levelPrice = new MemberLevelPrice();
            levelPrice.setLevelId(p.getLevelId());
            levelPrice.setLevelName(p.getLevelName());
            levelPrice.setPrice(p.getPrice());
            prices.add(levelPrice);
        }
        this.prices =prices;
    }

    /**
     * 删除时段
     *
     * @param id
     */
    public void deleteSupplyTimes(String id) {
        if (supplyTimes.indexOf(id) != -1) {
            JSONArray jsonArray = new JSONArray(supplyTimes);
            int subscript = 0;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String supplyTimeId = jsonObject.getString("id");
                if (StringUtils.equals(id, supplyTimeId)) {
                    subscript = i;
                    break;
                }
            }
            jsonArray.remove(subscript);
            supplyTimes = jsonArray.toString();
        }

    }

    public void removePrices(List<MemberLevelPrice> prices){
        prices.removeAll(prices);
    }








    /**
     * 获取时段提示
     *
     * @return
     */
    public String getMsg() {
        StringBuffer stringBuffer = new StringBuffer();
        if (supplyTimes != null && supplyTimes.indexOf("beginHour") != -1) {
            JSONArray jsonArray = new JSONArray(supplyTimes);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                int beginHour = jsonObject.getInt("beginHour");
                int endHour = jsonObject.getInt("endHour");
                int beginMinute = jsonObject.getInt("beginMinute");
                int endMinute = jsonObject.getInt("endMinute");
                if (i == 0) {
                    stringBuffer.append("添加失败！该商品供应时间段为：");
                }
                stringBuffer.append(beginHour);
                stringBuffer.append(":");
                stringBuffer.append(beginMinute);
                stringBuffer.append("--");
                stringBuffer.append(endHour);
                stringBuffer.append(":");
                stringBuffer.append(endMinute);
                if (i != jsonArray.length() - 1) {
                    stringBuffer.append(",");
                }
            }
        }
        return stringBuffer.toString();
    }


    /**
     * 判断商品供应时间段
     *
     * @return
     */
    public boolean checkSupplyTime() {
        ZoneId america = ZoneId.of("Asia/Shanghai");
        ZonedDateTime zonedDateTime = ZonedDateTime.now(america);
        int hour = zonedDateTime.getHour();
        int minute = zonedDateTime.getMinute();
        boolean status = false;
        if (supplyTimes != null && supplyTimes.indexOf("beginHour") != -1) {
            JSONArray jsonArray = new JSONArray(supplyTimes);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                int beginHour = jsonObject.getInt("beginHour");
                int endHour = jsonObject.getInt("endHour");
                int beginMinute = jsonObject.getInt("beginMinute");
                int endMinute = jsonObject.getInt("endMinute");
                if (hour < beginHour || hour > endHour) {
                    continue;
                }

                if (endHour == hour && hour == beginHour &&
                        minute >= beginMinute && minute <= endMinute) {
                    status = true;
                    break;
                } else if ((beginHour < hour && hour < endHour) ||
                        (beginHour == hour && hour < endHour && minute >= beginMinute) ||
                        (beginHour < hour && hour == endHour && minute <= endMinute)) {
                    status = true;
                    break;
                }
            }
        } else {
            status = true;
        }

        return status;
    }


    public String checkProduct(boolean isStockLimitSales, int qty) {
        String msg = null;
        if (productStatus == ProductStatus.OFF) {
            msg = "添加失败！商品已下架！";
        } else if (stockEnabled && isStockLimitSales && quantity - qty < 0) {
            msg = "添加失败！商品库存不足！";
        }
        return msg;
    }


}
